<template>
    <div class="docContainer">
      <el-col :span="5" style="padding-left: 10px;">
        <div class="left-body">
          <div class="title">
          案件文书
            <div class="search">
              <el-input v-model="typeFilter" placeholder="输入类型关键字" />
            </div>
          </div>
          <doc-aside ref="docAside">
            <div slot="current" class="type-list">
              <div
                class="type-item"
                :class="currIndex==index?'type-item-active':''"
                v-for="(item, index) in documents"
                :key="index"
                v-if="item.name.indexOf(typeFilter)!=-1"
                @click="getDocByName(item.name, index)">
                <span style="color:red;font-size:16px;margin-right:4px;" v-if="item.notNull">*</span>{{item.name}}
                <span class="icon-prompt">
                  <span class="status" :class="{complete:item.status == '已完成'}">{{item.status}}</span>
                  <i class="el-icon-link" v-if="item.appendix" style="margin-left:8px;font-size:16px;"></i>
                </span>
              </div>
            </div>
            <div slot="history" class="type-list">
              <div
                class="type-item"
                :class="hisIndex==index?'type-item-active':''"
                v-for="(item, index) in historyDoc"
                :key="index"
                v-if="item.contentName.indexOf(typeFilter)!=-1"
                @click="showHistoryDoc(index)">
                  {{item.contentName}}
              </div>
            </div>
          </doc-aside>
        </div>
      </el-col>
      <el-col :span="14" style="padding-left:10px;">
        <div class="document">
          <div class="title">
            {{docName}}  -预览
            <el-button type="primary" size="mini" @click="saveDoc" style="float:right;margin:8px 0 0 8px;">打印</el-button>
            <el-button type="primary" size="mini" @click="completeDoc" style="float:right;margin-top:8px;">完成</el-button>
            <el-button type="primary" size="mini" @click="saveDoc" style="float:right;margin-top:8px;">暂存</el-button>
          </div>
          <div v-html="detailUrl" class="doc-detail" style="height:calc(100% - 40px)"></div>
        </div>
      </el-col>
      <el-col :span="5" style="padding:0 10px;">
        <div class="appendix">
          <div class="title" style="padding-right:10px;">
            {{docName}} - 附件
            <el-upload
              ref="elUpload"
              class="upload-demo"
              action="/api/caseDocCase/upload"
              :data="param"
              :show-file-list="false"
              accept=".jpg,.png,.bmp,.jpeg,.psd"
              :on-success="uploadSuccess"
              style="float:right;border:0">
              <el-button size="small" type="primary">附件上传</el-button>
            </el-upload>
          </div>
          <viewer :images="fileList">
            <div v-for="(src, index) in fileList" :key="index" class="images">
              <div class="img-remove" title="点击删除附件" @click="deleteImg(src)"><i class="el-icon-delete" ></i></div>
              <img :src="serverRoot+src.url"  />
            </div>
            <div v-if="!fileList" class="prompt">
              <span>无附件</span>
            </div>
          </viewer>
        </div>
      </el-col>
      <div class="clearfix"></div>
    </div>
</template>
<script>
import dictCache from "@/assets/utils/cache-dict-util";
import caseApi from "@/api/system/case";
import utils from '@/assets/utils/zhzf-util';
import caseDocApi from "@/api/system/caseDoc";
import workflowApi from "@/api/system/workflow";
import deptApi from "@/api/system/dept";
import docApi from "@/api/system/doc";
import docAside from "@/views/comps/zhzf/doc-aside"
import { mapActions } from "vuex";
import moment from 'moment';
import "viewerjs/dist/viewer.css";
import Vue from "vue";
import Viewer from "v-viewer";
Vue.use(Viewer);
export default {
  props:[],
  data() {
    return {
      documents:[],
      historyDoc:[],
      docName:'',
      detailUrl:null,
      visible:false,
      detail:{},
      newData:null,
      docId:null,
      docList:null,
      param:null,
      fileList:[],
      typeFilter:'',
      currIndex:0,
      hisIndex:null,
      dialogVisible:false,
      dialogImageUrl: '',
      serverRoot:process.env.VUE_APP_API,
    };
  },
  components:{
    docAside
  },
  methods: {
    ...mapActions("d2admin/page", ["close"]),
    async initPage(detail){
      if(!detail||!detail.caseAccessId){
        console.warn('当前页面必须有案件信息');
        return;
      }
      this.detail=detail;
      await this.getDocument();
      await this.initDocStatus();
      await this.getHistoryDoc();
      if(this.documents.length){
        this.getDocByName(this.documents[0].name,0);
      }
    },
    async getDocument() {
      this.documents=[];
      //获取动态表单重定义的文书名称
      let resp = await workflowApi.taskStartForm({
        id: this.detail.workNodeId
      });
      if (resp) {
        let data = resp.data;
        for (let i = 0; i < data.length; i++) {
          if (data[i].id == "current_link") {
            this.current_link = data[i].name; //当前环节
          } else if (data[i].id == "next_link") {
            this.next_link = data[i].name; //下一环节
          } else {
            this.documents.push({name:data[i].name, appendix:0, status:'未填写', notNull:data[i].required, key:data[i].id});
          }
        }
      }
    },
    async initDocStatus(){
      for(let i = 0; i < this.documents.length; i++){
        let resp = await caseDocApi.select({contentName:this.documents[i].name, caseBasicinfoId:this.detail.caseAccessId});
        if(resp){
          this.documents[i].status = resp.data[0].status;
          if(resp.data[0].fileUrl){
            this.documents[i].appendix = 1;
          }
        }
      }
    },
    async getHistoryDoc(){  //获取已完成的文书
      let resp = await caseDocApi.select({status:'已完成', caseBasicinfoId:this.detail.caseAccessId})
      if(resp){
        this.historyDoc = resp.data;
        console.log(this.historyDoc);
      }
    },
    async getDocByName(name, index){ //根据文书名称获取文书
      this.currIndex = index;
      this.hisIndex = null;
      let resp = await caseDocApi.select({contentName:name, caseBasicinfoId:this.detail.caseAccessId});
      if(resp){
        this.param = resp.data[0];
        this.detailUrl = this.param.detailUrl;
        this.docName = this.param.contentName;
        this.fileList = JSON.parse(this.param.fileUrl);
        this.dataReplace();
      }
    },
    showHistoryDoc(index){
      this.currIndex = null;
      this.hisIndex = index;
      this.detailUrl = this.historyDoc[index].detailUrl;
      console.log(this.detailUrl);
    },
    dataReplace(){
       this.$nextTick(() => {
        if (document.querySelector('.case-doc-date')) { //日期
          document.querySelector('.case-doc-date').innerHTML = moment(this.detail.createTime).format('YYYY年MM月DD日');
        }
        if (document.querySelector('.case-doc-dateTime')) {  //时间
          document.querySelector('.case-doc-dateTime').innerHTML = moment(this.detail.createTime).format('YYYY年MM月DD日 HH时MM分') || moment().format('YYYY年MM月DD日 HH时MM分');
        }
        if (document.querySelector('.case-doc-party')) {  //当事人
          document.querySelector('.case-doc-party').innerHTML = this.detail.party
        }
        if (document.querySelector('.case-doc-party-tel')) {  //当事人联系方式
          document.querySelector('.case-doc-party-tel').innerHTML = this.detail.partyTel
        }
        if (document.querySelector('.case-doc-party-sex')) {  //当事人性别
          document.querySelector('.case-doc-party-sex').innerHTML = this.detail.partySex
        }
        if (document.querySelector('.case-doc-party-nation')) {  //当事人民族
          document.querySelector('.case-doc-party-nation').innerHTML = this.detail.partNation
        }
        if (document.querySelector('.case-doc-party-age')) {  //当事人年龄
          document.querySelector('.case-doc-party-age').innerHTML = this.detail.partyAge
        }
        if (document.querySelector('.case-doc-party-card-no')) {  //当事人身份证号
          document.querySelector('.case-doc-party-card-no').innerHTML = this.detail.partyCardNo
        }
        if (document.querySelector('.case-doc-party-qua-num')) {  //当事人资格编号
          document.querySelector('.case-doc-party-qua-num').innerHTML = this.detail.partyQuaNum
        }
        if (document.querySelector('.case-doc-party-lega')) {  //当事人法定代表
          document.querySelector('.case-doc-party-lega').innerHTML = this.detail.partyLega
        }
        if (document.querySelector('.case-doc-party-post')) {  //当事人职务
          document.querySelector('.case-doc-party-post').innerHTML = this.detail.partyPost
        }
        if (document.querySelector('.case-doc-party-type')) {  //当事人类型
          document.querySelector('.case-doc-party-type').innerHTML = this.detail.partyType
        }
        if (document.querySelector('.case-doc-party-address')) {  //联系地址
          document.querySelector('.case-doc-party-address').innerHTML = this.detail.partyAddress
        }
        if (document.querySelector('.case-doc-case-type')) {  //案件类型
          document.querySelector('.case-doc-case-type').innerHTML = this.detail.caseType
        }
        if (document.querySelector('.case-doc-filling-place')) {  //立案地点
          document.querySelector('.case-doc-filling-place').innerHTML = this.detail.caseFillingPlace
        }
        if (document.querySelector('.case-doc-cause-address')) {  //案发地点
          document.querySelector('.case-doc-cause-address').innerHTML = this.detail.caseCauseAddress
        }
        if (document.querySelector('.case-doc-case-cause-time')) {  //案发时间
          document.querySelector('.case-doc-case-cause-time').innerHTML = this.detail.caseCauseTime
        }
        if (document.querySelector('.case-doc-case-facts')) {  //案由
          document.querySelector('.case-doc-case-facts').innerHTML = this.detail.caseFacts
        }
        if (document.querySelector('.case-doc-register-source')) {  //案件来源
          document.querySelector('.case-doc-register-source').innerHTML = this.detail.registerSource
        }
        if (document.querySelector('.case-doc-case-num')) {  //案件编号
          document.querySelector('.case-doc-case-num').innerHTML = this.detail.caseNum
        }
        if (document.querySelector('.case-doc-case-illegal-facts')) {  //违法事实
          document.querySelector('.case-doc-case-illegal-facts').innerHTML = this.detail.illegalFacts
        }
        if (document.querySelector('.case-doc-case-organ-name')) {  //机构名称
          document.querySelector('.case-doc-case-organ-name').innerHTML = this.detail.caseOrganName
        }
        if (document.querySelector('.case-doc-reporter')) {  //举报人
          document.querySelector('.case-doc-reporter').innerHTML = this.detail.reporter
        }
        if (document.querySelector('.case-doc-reporter-tel')) {  //举报人电话
          document.querySelector('.case-doc-reporter-tel').innerHTML = this.detail.reporterTel
        }
        if (document.querySelector('.case-doc-vehicle-axles-number')) {  //车轴数量
          document.querySelector('.case-doc-vehicle-axles-number').innerHTML = this.detail.vehicleAxlesNumber
        }
        if (document.querySelector('.case-doc-vehicle-id-color')) {  //车牌颜色
          document.querySelector('.case-doc-vehicle-id-color').innerHTML = this.detail.vehicleIdColor
        }
        if (document.querySelector('.case-doc-vehicle-ship-id')) {  //车船ID
          document.querySelector('.case-doc-vehicle-ship-id').innerHTML = this.detail.vehicleShipId
        }
        if (document.querySelector('.case-doc-vehicle-ship-type')) {  //车船型
          document.querySelector('.case-doc-vehicle-ship-type').innerHTML = this.detail.vehicleShipType
        }
        if (document.querySelector('.case-doc-zfml')) {  //执法门类
          document.querySelector('.case-doc-zfml').innerHTML = this.detail.zfml
        }
        if (document.querySelector('.case-doc-department')) {  //执法部门
          document.querySelector('.case-doc-department').innerHTML = this.detail.department
        }
        if (document.querySelector('.case-doc-vehicle-ship-rated-ton')) {  //货物名称
          document.querySelector('.case-doc-vehicle-ship-rated-ton').innerHTML = this.detail.vehicleShipRatedTon
        }
        if (document.querySelector('.case-doc-vehicle-ship-goods')) {  //核定吨位
          document.querySelector('.case-doc-vehicle-ship-goods').innerHTML = this.detail.vehicleShipGoods
        }
        if (document.querySelector('.case-doc-illegal-law')) {  //违反条例
          document.querySelector('.case-doc-illegal-law').innerHTML = this.detail.illegalLaw
        }
        if (document.querySelector('.case-doc-punish-amount')) {  //拟处罚金额
          document.querySelector('.case-doc-punish-amount').innerHTML = this.detail.punishAmount
        }
        if (document.querySelector('.case-doc-discretionid')) {  //自由裁量权
          document.querySelector('.case-doc-discretionid').innerHTML = this.detail.discretionid
        }
        if (document.querySelector('.case-doc-illegal-punishment-standard')) {  //违法处罚依据
          document.querySelector('.case-doc-illegal-punishment-standard').innerHTML = this.detail.illegalPunishmentStandard
        }
        if (document.querySelector('.case-doc-road-transport-license')) {  //道路运输经营许可证
          document.querySelector('.case-doc-road-transport-license').innerHTML = this.detail.illegalPunishmentStandard
        }
        if (document.querySelector('.case-doc-vehicle-register')) {  //车籍所在地
          document.querySelector('.case-doc-vehicle-register').innerHTML = this.detail.vehicleRegister
        }
        if (document.querySelector('.case-doc-organ-contactor')) {  //执法机构联系人
          document.querySelector('.case-doc-organ-contactor').innerHTML = this.detail.organContactor
        }
        if (document.querySelector('.case-doc-organ-tel')) {  //执法机构电话
          document.querySelector('.case-doc-organ-tel').innerHTML = this.detail.organTel
        }
        if (document.querySelector('.case-doc-organ-zipcode')) {  //执法机构邮编
          document.querySelector('.case-doc-organ-zipcode').innerHTML = this.detail.organZipcode
        }
        if (document.querySelector('.case-doc-organ-address')) {  //执法机构联系地址
          document.querySelector('.case-doc-organ-address').innerHTML = this.detail.organAddress
        }
       })
    },
    async uploadSuccess(resp){  //上传成功\
      if(resp.ok){
        this.fileList = JSON.parse(resp.data);
        if(this.fileList.length>0){
          this.documents[this.currIndex].appendix = 1;
        }
      }
      this.$refs.elUpload.clearFiles();
    },
    async deleteImg(img){  //删除图片
      let res = await caseDocApi.delUpload({id:this.param.id, fileUrl:img.url});
      if(res.ok){
        utils.showTips(`附件删除${res.ok?"成功":"失败"}`,res.ok);
        console.log(res.data);
        if(res.data){
          this.fileList = JSON.parse(res.data);
        }else{
          this.fileList = null
        }
        if(!this.fileList){
          this.documents[this.currIndex].appendix = 0;
        }
      }
      this.$refs.elUpload.clearFiles();
    },
    async completeDoc(){   //完成文书
      var temp = document.querySelector('.doc-detail').innerHTML;
      this.param.detailUrl = temp;
      this.param.status = "已完成";
      let resp = await caseDocApi.mod(this.param); //提交数据
      if (resp) {
        let ok = resp.ok;
        if(ok){
            this.$notify({title: '操作提示', message: ok ? '案件文档保存成功' : '案件文档保存失败', type: ok ? 'success' : 'error'});
            this.documents[this.currIndex].status = "已完成";
        }
      }
    },
    async saveDoc(){    //暂存文书
      var temp = document.querySelector('.doc-detail').innerHTML;
      this.param.detailUrl = temp;
      this.param.status = "暂存";
      let resp = await caseDocApi.mod(this.param); //提交数据
      if (resp) {
        let ok = resp.ok;
        if(ok){
            this.$notify({title: '操作提示', message: ok ? '案件文档保存成功' : '案件文档保存失败', type: ok ? 'success' : 'error'});
            this.documents[this.currIndex].status = "暂存";
        }
      }
    },
  }
};
</script>
<style lang="scss">
.docContainer{
  $page-height:calc(100vh - 230px);
  padding:20px 0;
  .left-body{
    overflow: auto;
    height: $page-height;
    border:1px solid #ccc;
  }
  .document{
    position: relative;
    overflow: auto;
    border:1px solid #ccc;
    height: $page-height;
    .doc-detail{
      padding:15px 35px;
    }
  }
  .appendix{
    height: $page-height;
    border:1px solid #ccc;
    overflow: auto;
    img{
      width:calc(100% - 8px);
      border:4px solid #ccc;
    }
    .images{
      position: relative;
    background: #ddd;
    padding: 5px;
      .img-remove{
        position: absolute;
        cursor: pointer;
        font-size: 20px;
        right: 10px;
        top:10px;
        color: red;
        display: none;
      }
    }
    .images:hover{
      .img-remove{
        display: block;
      }
    }
    .prompt{
      line-height: 10;
      text-align: center;
      font-size: 20px;
      font-weight: 700;
      color:#ccc;
    }
  }
  .search {
    float: right;
    width:calc(100% - 80px);
    input {
      height: 33px;
    }
  }
  .type-list{
    .type-item {
      padding: 0 15px;
      border-bottom: 1px solid #ccc;
      line-height: 35px;
      height: 35px;
      cursor: pointer;
      .icon-prompt{
        // display:inline-block;
        float:right;
        // margin-right:4px;
      }
    }
    .status{
      font-size:12px;
      color:#409EFF
    }
    .complete{
      color:#67C23A;
    }
    .type-item-active,
    .type-item:hover {
      background: #c9e6ff;
    }

    .type-item-active {
      color: #027be3;
    }
  }
  .clearfix{
    content:'';
    clear:both;
  }
}
</style>
